"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '07/09/2022'
    comment: 工程全局使用的变量以及函数等
"""
import functools
import os
import logging

from sqlalchemy import create_engine
from sqlalchemy.orm import Session

from config import Config
from project.core.log import Log, LogConfig
from contextlib import contextmanager
from project.third_part.okex import Okex

# ====================日志对象部分====================
logging.basicConfig(level=Config.LOGGER_LEVEL)  # 项目日志级别

# 普通日志
logger = Log(logger_name=str(os.getpid()), log_config=LogConfig(**Config.LOGGER), display_console=Config.DISPLAY_CONSOLE)

# 数据库连接
DATABASE_URL = f"postgresql://{Config.DB_OPTIONS['user']}:{Config.DB_OPTIONS['password']}@{Config.DB_OPTIONS['host']}:{Config.DB_OPTIONS['port']}/{Config.DB_OPTIONS['db']}"
engine = create_engine(DATABASE_URL, echo=True, future=True)


@contextmanager
def session_maker():
    """ 从session pool
    :return:
    """
    session = Session(engine)
    try:
        yield session
    except Exception as ex:
        session.rollback()
        raise ex
    finally:
        session.close()


def with_session():
    """
    :return:
    """
    def handle_func(func):
        @functools.wraps(func)
        def wrap_func(*args, **kwargs):
            try:
                with session_maker() as session:
                    kwargs['session'] = session
                    ret = func(*args, **kwargs)
                return ret
            except Exception as ex:
                raise ex

        return wrap_func

    return handle_func


# okex数据采集客户端
okex_client = Okex()

# okex交易客户端
okex_trade_client = Okex()
